<?php

class News extends CActiveRecord
{
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function tableName()
	{
		return '{{news}}';
	}

	public function rules()
	{
		$languages = Languages::model()->getLanguageCodes();
		
		$required = 'active';
		foreach ($languages as $lang)
		{
			$required .= ', title_'.$lang.', body_'.$lang.', preview_'.$lang;
		}
		return array(
			array($required, 'required'),
			array('active', 'numerical', 'integerOnly'=>true),
			array('id, active, creation_date', 'safe', 'on'=>'search'),
		);
	}

	public function relations()
	{
		return array(
		);
	}

	public function attributeLabels()
	{
		$languages = Languages::model()->getLanguageCodes();
		
		$labels = array(
			'id' => 'ID',
			'active' => tt('Active'),
			'creation_date' => tt('Creation Date'),
		);
		foreach($languages as $lang)
		{
			$labels['title_'.$lang] = tt('Title');
			$labels['preview_'.$lang] = tt('Preview');
			$labels['body_'.$lang] = tt('Body');
		}
		
		return $labels;
	}

	public function search()
	{
		$criteria=new CDbCriteria;

		$languages = Languages::model()->getLanguageCodes();
		foreach ($languages as $lang)
		{
			$criteria->compare('title_'.$lang,$this->{'title_'.$lang},true);
			$criteria->compare('preview_'.$lang,$this->{'preview_'.$lang},true);
			$criteria->compare('body_'.$lang,$this->{'body_'.$lang},true);
		}
		$criteria->order = 'creation_date ASC';

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>param('adminPaginationPageSize', 20),
			),
		));
	}
	
	public function behaviors(){
		return array(
			'AutoTimestampBehavior' => array(
				'class' => 'zii.behaviors.CTimestampBehavior',
				'createAttribute' => 'creation_date',
				'updateAttribute' => null,
			),
		);
	}

	public function beforeSave(){
		if($this->isNewRecord){
			$this->active = 1;
		}
	
		return parent::beforeSave();
	}
	
}